/**
 iTextUploader
 (C) 2008 Asgl (myselftdev@gmail.com)

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; version 2
 of the License.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

/* Revision: $Id: iTextUploader.m 14 2008-07-25 10:41:56Z myselftdev $ */

#import "iTextUploader.h"

#define UPLOAD_FILE "~/Library/SMS/sms.db"
#define DATA_FILE "~/Library/Preferences/it.youarchive.itextuploader.plist"

int main(int argc, char **argv)
{
	NSAutoreleasePool *autoreleasePool = [[ NSAutoreleasePool alloc ] init];
    
    int returncode = UIApplicationMain(argc, argv, @"MyApp", @"MyApp");
    
    [ autoreleasePool release ];
    
    return returncode;
}

@implementation MyApp

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	
    window = [ [ UIWindow alloc ] initWithContentRect:
			  [ UIHardware fullScreenApplicationContentRect ]
			  ];
	
    CGRect rect = [ UIHardware fullScreenApplicationContentRect ];
    rect.origin.x = rect.origin.y = 0.0f;
	
    mainView = [ [ MainView alloc ] initWithFrame: rect];
	
    [ window setContentView: mainView ];
    [ window orderFront: self ];
    [ window makeKey: self ];
    [ window _setHidden: NO ];
	
	[pool drain];
}

- (void) dealloc
{
	[window release];
	[mainView release];
	[self dealloc];
	[super dealloc];
}

@end

@implementation MainView
- (id)initWithFrame:(CGRect)rect {
	
    if ((self == [ super initWithFrame: rect ]) != nil) {
    	currentPage = 0;
		
        navBar = [ self createNavBar: rect ];
        [self setNavBar];
        
        CGRect viewRect = CGRectMake(rect.origin.x, rect.origin.y,
									 rect.size.width, rect.size.height - 48.0);
        
        mainText = [[NSString alloc] initWithContentsOfFile:@"/Applications/iTextUploader.app/MainText.html"];
        
        textView = [ [ UITextView alloc ] initWithFrame: viewRect ];
        /*[ textView setTextSize: 18 ];
        [ textView setHTML: mainText];
        [ textView setEditable: NO];*/
        [ textView setText: @"iTextUploader\n\nWelcome to iTextUploader! This native iPhone application allows you to upload your sms database directly to YouArchive.It, over the air!\n\nBefore you start, please go to the settings page and fill in your login data for YouArchive.It.\nDon't have an account yet? Go to http://youarchive.it with your PC or your iPhone and get one now! It's FREE!"];
        
        prefsPanel = [ [ PreferencesPanel alloc ] initWithFrame: viewRect ];
        [ prefsPanel reloadData ];
        [ prefsPanel setDataFilename: [@DATA_FILE stringByExpandingTildeInPath]];
		NSLog(@"Data filename: %@", [@DATA_FILE stringByExpandingTildeInPath]);
        [ prefsPanel loadData];
        
        aboutView = [ [ UITextView alloc ] initWithFrame: viewRect ];
        /*[ aboutView setTextSize: 18 ];
        [ aboutView setHTML: [NSString stringWithContentsOfFile:@"/Applications/iTextUploader.app/About.html"] ];
        [ aboutView setEditable: NO];*/
        [ aboutView setText: @"iTextUploader version 0.2\n\n(C)2008 Asgl (myselftdev@gmail.com)\n\nhis program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.\nThe author takes absolutly NO responsibility/warranty for any possible results caused by this application.\n\nIf you think this app is good to you, please consider making a donation.\n\niTextUploder contains some code from iFlickr (http://iflickr.wordpress.com/), which is released under GNU General Public License version 2.\n\nSpecial thanks also go to:\n- The p2pforum.it community, which helped me to solve some problems with Objective-C\n- People at #iphone-dev on irc.osx86.hu for their precious help with unofficial toolchain\n- Jonathan A. Zdziarski aka NerveGas for his fantastic book about iPhone programming"];
        
        //[ self addSubview: textView ];
        transView = [ [ UITransitionView alloc ]
					 initWithFrame: CGRectMake(rect.origin.x, rect.origin.y + 48.0, rect.size.width, rect.size.height - 48.0) ];
        [ self addSubview: transView ];
        [ self addSubview: navBar ];
        [ self flipTo: 0];
    }
	
    return self;
}

- (void) setNavBar
{
	// Default page
	if(currentPage == 0)
	{
		[ navBar showLeftButton:@"Settings" withStyle: 0
					rightButton:@"Upload" withStyle: 3];
	}
	// Settings
	else if(currentPage == 1)
	{
		[ navBar showLeftButton:@"Save" withStyle: 2
					rightButton:@"About" withStyle: 0];
	}
	// About
	else if(currentPage == 2)
	{
		[ navBar showLeftButton:@"Return" withStyle: 2
					rightButton:nil withStyle: 0];
	}
}

- (void)flipTo:(int)page
{
	if(page == 1)
	{
		[ transView transition: 6
					  fromView: textView toView: prefsPanel ];
	}
	else if(page == 0)
	{
		//[ textView setHTML: mainText];
		
		[ transView transition: 6
					  fromView: prefsPanel toView: textView ];
	}
	else if(page == 2)
	{
		[ transView transition: 6
					  fromView: prefsPanel toView: aboutView ];
	}
	
	currentPage = page;
	
	[self setNavBar];
}

- (UINavigationBar *)createNavBar:(CGRect)rect {
    UINavigationBar *newNav = [ [UINavigationBar alloc]
							   initWithFrame:
							   CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, 48.0)
							   ];
	
    [ newNav setDelegate: self ];
    [ newNav enableAnimation ];
	
    /* Add our title */
    navItem = [ [UINavigationItem alloc]
			   initWithTitle:@"iTextUploader" ];
    [ newNav pushNavigationItem: navItem ];
	
    return newNav;
}

- (void)navigationBar:(UINavigationBar *)navbar buttonClicked:(int)button
{
	if (button == 0) /* Right button */
    {	
		if(currentPage == 0)
    	{
    		[self uploadFile];
    	}
    	else if(currentPage == 1)
    	{
    		[self flipTo: 2];
    	}
    }
    else if(button == 1) /* Left button */
    {
    	if(currentPage == 0 || currentPage == 2)
    	{
    		[self flipTo: 1];
    	}
    	else if(currentPage == 1)
    	{
    		[prefsPanel saveData];
 			[self flipTo: 0];
    	}
    }
}

- (void) uploadFile
{
	FileUpload * upload = [[FileUpload alloc] init];
	[upload setUsername:[prefsPanel username] password:[prefsPanel password]];
	NSLog(@"File to upload: %@", [@UPLOAD_FILE stringByExpandingTildeInPath]);
	NSString *result = [upload uploadFile:[@UPLOAD_FILE stringByExpandingTildeInPath]];
	
	NSLog(@"Result: %@", result);
	
	NSRange position = [result rangeOfString:@"\n"];
	
	NSString *statusCode;
	NSString *message;
	NSString *status;
	NSString *image;
	
	if(position.location != NSNotFound)
	{
		statusCode = [result substringToIndex:position.location];
		message = [result substringFromIndex:(position.location + 1)];
	}
	else
	{
		statusCode = [NSString stringWithString:result];
		message = @"&nbsp;";
	}
	
	if([statusCode isEqualToString:@"LOGIN ERROR"])
	{
		status = @"Login error";
		image = @"error";
	}
	else if([statusCode isEqualToString:@"FATAL ERROR"])
	{
		status = @"Fatal error";
		image = @"error";
	}
	else if([statusCode isEqualToString:@"LOGIN EMPTY"])
	{
		status = @"Login error";
		image = @"error";
		message = @"Username and/or password empty. Please go to the Settings page and insert your login data for YouArchive.It WebApp.<br />If you don't have an username on YouArchive.It WebApp, you can register for free at http://youarchive.it.";
	}
	else if([statusCode isEqualToString:@"FAIL"])
	{
		status = @"Upload failed";
		image = @"error";
	}
	else if([statusCode isEqualToString:@"CONNECTION ERROR"])
	{
		status = @"Connection error";
		image = @"error";
	}
	else if([statusCode isEqualToString:@"OK"])
	{
		status = @"Upload OK!";
		image = @"ok";
	}
	else
	{
		status = @"Unknown error";
		image = @"error";
	}
	
	NSString *HTMLFile = [NSString stringWithContentsOfFile:@"/Applications/iTextUploader.app/Message.html"];
	
	//[textView setHTML: [NSString stringWithFormat:HTMLFile, [NSString stringWithFormat:@"file:///Applications/iTextUploader.app/%@.png",image], status, message]];

	[textView setText: [NSString stringWithFormat:@"Status: %@\nMessage: %@", status, message]];
	
	[result release];
	[upload release];
}

- (void)dealloc
{
	[ navBar release ];
    [ navItem release ];
    [ transView release ];
    [ textView release ];
    [ prefsPanel release];
    [ aboutView release ];
    [ mainText release];
    [ self dealloc ];
    [ super dealloc ];
}

@end